package com.example.app.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;

/**
 * AES 加密解密工具类（基于 Hutool）
 */
@Slf4j
@Component
public class AesUtil {

    @Value("${app.client.secretKey}")  // 从配置文件获取密钥
    private String secretKey;
    private static AES aesInstance;


    /**
     * 初始化 AES 实例
     */
    @PostConstruct
    public void init() {
        aesInstance = SecureUtil.aes(secretKey.getBytes(StandardCharsets.UTF_8));
        log.info("AES 密钥初始化成功");
    }

    /**
     * AES 加密（Base64 编码）
     * @param plaintext 明文
     * @return 加密后的 Base64 编码字符串
     */
    public String encrypt(String plaintext) {
        try {
            return aesInstance.encryptBase64(plaintext, StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.error("AES 加密失败: {}", e.getMessage());
            throw new RuntimeException("AES 加密失败", e);
        }
    }

    /**
     * AES 解密（Base64 编码密文）
     * @param ciphertext 密文
     * @return 解密后的明文
     */
    public String decrypt(String ciphertext) {
        try {
            return aesInstance.decryptStr(ciphertext, StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.error("AES 解密失败: {}", e.getMessage());
            throw new RuntimeException("AES 解密失败", e);
        }
    }


    /**
     * AES加密（支持返回Base64编码密文）
     * @param content 待加密的内容
     * @param encryptKey 加密密钥
     * @return 加密后的Base64编码字符串
     * @throws Exception
     */
    public String aesEncrypt(String content, String encryptKey) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(encryptKey.getBytes());
            kgen.init(128, random);
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));
            byte[] encryptedBytes = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
            return Base64.encode(encryptedBytes);
        } catch (Exception e) {
            log.error("加密失败", e);
        }
        return "";
    }

    /**
     * AES解密（支持Base64编码密文）
     * @param encryptStr 待解密的Base64编码密文
     * @param decryptKey 解密密钥
     * @return 解密后的string
     * @throws Exception
     */
    public String aesDecrypt(String encryptStr, String decryptKey) {
        try {
            byte[] encryptedBytes = Base64.decode(encryptStr);
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(decryptKey.getBytes());
            kgen.init(128, random);
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));
            byte[] decryptBytes = cipher.doFinal(encryptedBytes);
            return new String(decryptBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.error("解密失败", e);
        }
        return "";
    }

}